const express = require("express");
const boom = require("boom");
const userRouter = require("./system/user");
const menuRouter = require("./system/menu");
const deptRouter = require("./system/dept");
const roleRouter = require("./system/role");
const areaRouter = require("./space/teachingArea");
const facilityRouter = require("./space/facility");
const classroomRouter = require("./space/classroom");
const semesterRouter = require("./educational/semester");
const classSectionRouter = require("./educational/classSection");
const classRouter = require("./educational/class");
const fixRouter = require("./space/fix");
const { CODE_ERROR } = require("../utils/constant");
const Result = require("../models/Result");

// 注册路由
const router = express.Router();

router.get("/", function (req, res) {
  res.send("欢迎来到tangweize的后台管理系统");
});

router.use("/api/users", userRouter);
router.use("/api/menu", menuRouter);
router.use("/api/dept", deptRouter);
router.use("/api/roles", roleRouter);
router.use("/api/teachingArea", areaRouter);
router.use("/api/facility", facilityRouter);
router.use("/api/classroom", classroomRouter);
router.use("/api/semester", semesterRouter);
router.use("/api/classSection", classSectionRouter);
router.use("/api/class", classRouter);
router.use("/api/fix", fixRouter);

// 404处理中间件，下面的指令会拦截一切请求，但是只要是正常请求都会在前面得到响应
// 换言之，只有404错误的请求才会到达这一步
router.use((req, res, next) => {
  next(boom.notFound("接口不存在"));
});

// 自定义路由异常处理中间件(已加入TOKEN异常的特殊处理方法)
router.use((err, req, res, next) => {
  if (err.name === "UnauthorizedError") {
    const { status = 401, message } = err;
    new Result(null, "Token验证失败", {
      error: status,
      errMsg: message,
    }).jwtError(res.status(status));
  } else {
    const msg = (err && err.message) || "系统错误";
    const statusCode = (err.output && err.output.statusCode) || 500;
    const errorMsg =
      (err.output && err.output.payload && err.output.payload.error) ||
      err.message;
    new Result(null, msg, {
      error: statusCode,
      errorMsg,
    }).fail(res.status(statusCode));
  }
});

module.exports = router;
